﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Configuration;
using Microsoft.TeamFoundation.WorkItemTracking.Client;
using Microsoft.TeamFoundation.Client;
using Microsoft.TeamFoundation.Server;

using System.Data;
using System.Data.SqlClient;
using System.Globalization;
using System.Net;

namespace GTA.ResourceAccess
{
    public abstract class BaseResourceAccess
    {
        #region Constructors
        public BaseResourceAccess()
        {
            teamSystem = TeamSystemProviderFactory.GetInstance();
        }
        #endregion

        #region TeamSystem Integration Resources
        #region Local Objects
        private static ITeamSystemProvider teamSystem;
        #endregion

        #region Inicialization
        public static WorkItemStore GetWorkItemStore()
        {
            return teamSystem.GetWorkItemStore();
        }
        protected static IGroupSecurityService GetGroupSecurityService()
        {
            return teamSystem.GetGroupSecurityService();
        }
        #endregion

        #region Execution Methods
        public WorkItemCollection ExecuteQuery(string wiql)
        {
            return teamSystem.ExecuteQuery(wiql);
        }
        public void StartTeamSystemInstance()
        {
            teamSystem.StartTeamSystemInstance();
        }
        #endregion
        #endregion

        #region DataBase Control
        #region Atributos
        private SqlConnection connection;
        private SqlCommand command;
        protected SqlDataReader reader;
        private SqlDataAdapter adapter;
        private DataSet dataSet = null;
        protected String sqlCommand = String.Empty;
        protected SqlTransaction transaction;
        #endregion

        #region Obter String Conexão
        private String getStringConnection()
        {
#if DEBUG
            return System.Configuration.ConfigurationManager.ConnectionStrings["ConnectionStringDEV"].ToString();
#else
            return System.Configuration.ConfigurationManager.ConnectionStrings["ConnectionStringPROD"].ToString();
#endif
        }
        #endregion

        #region Métodos de Conexão
        private void OpenConnection()
        {
            try
            {
                connection = new SqlConnection(getStringConnection());
                connection.Open();
            }
            catch (Exception)
            {
                connection = null;
                throw;
            }
        }
        private void CloseConnection()
        {
            try
            {
                if (connection != null)
                    connection.Close();
            }
            catch (Exception)
            {
                connection = null;
                throw;
            }
        }
        #endregion

        protected SqlTransaction OpenTransaction()
        {
            OpenConnection();
            return connection.BeginTransaction();
        }
        public void StartTransaction()
        {
            OpenConnection();
            transaction = connection.BeginTransaction();
        }
        public void CommitTransaction()
        {
            if (transaction != null)
                transaction.Commit();
        }
        public void RollBackTransaction()
        {
            if (transaction != null)
                transaction.Rollback();
        }

        #region Métodos de ExecuteNonQuery
        protected void ExecuteNonQuery(String procedure)
        {
            OpenConnection();
            command = new SqlCommand(procedure, connection);
            command.ExecuteNonQuery();
            CloseConnection();
        }
        protected void ExecuteNonQuery(String procedure, SqlParameter[] parametros)
        {
            OpenConnection();
            command = new SqlCommand(procedure, connection);
            command.CommandType = CommandType.StoredProcedure;
            if (parametros != null)
                command.Parameters.AddRange(parametros);
            command.ExecuteNonQuery();
            CloseConnection();
        }
        protected void ExecuteNonQuery(SqlTransaction transaction, String procedure)
        {
            command = new SqlCommand(procedure, connection);
            command.CommandType = CommandType.StoredProcedure;
            command.Transaction = transaction;
            command.ExecuteNonQuery();
        }
        protected void ExecuteNonQuery(SqlTransaction transaction, String procedure, SqlParameter[] parametros)
        {
            command = new SqlCommand(procedure, connection);
            command.CommandType = CommandType.StoredProcedure;
            if (parametros != null)
                command.Parameters.AddRange(parametros);
            command.Transaction = transaction;
            command.ExecuteNonQuery();
        }
        #endregion

        #region Métodos de ExecuteScalar
        protected Int32 ExecuteScalar(String procedure)
        {
            OpenConnection();
            command = new SqlCommand(procedure, connection);
            command.CommandType = CommandType.StoredProcedure;
            Object result = command.ExecuteScalar();
            CloseConnection();
            return Convert.ToInt32(result, CultureInfo.CurrentCulture);
        }
        protected Int32 ExecuteScalar(SqlTransaction transaction, String procedure)
        {
            command = new SqlCommand(procedure, connection);
            command.CommandType = CommandType.StoredProcedure;
            command.Transaction = transaction;
            Object result = command.ExecuteScalar();
            return Convert.ToInt32(result, CultureInfo.CurrentCulture);
        }
        protected Int32 ExecuteScalar(String procedure, SqlParameter[] parametros)
        {
            OpenConnection();
            command = new SqlCommand(procedure, connection);
            command.CommandType = CommandType.StoredProcedure;
            if (parametros != null)
                command.Parameters.AddRange(parametros);
            Object result = command.ExecuteScalar();
            CloseConnection();
            return Convert.ToInt32(result, CultureInfo.CurrentCulture);
        }
        protected Int32 ExecuteScalar(SqlTransaction transaction, String procedure, SqlParameter[] parametros)
        {
            command = new SqlCommand(procedure, connection);
            command.CommandType = CommandType.StoredProcedure;
            if (parametros != null)
                command.Parameters.AddRange(parametros);
            command.Transaction = transaction;
            Object result = command.ExecuteScalar();
            return Convert.ToInt32(result, CultureInfo.CurrentCulture);
        }
        #endregion

        #region Métodos de Leitura de Dados

        #region Execute Query Reader
        protected SqlDataReader ExecuteReader(String procedure)
        {
            OpenConnection();
            command = new SqlCommand(procedure, connection);
            command.CommandType = CommandType.StoredProcedure;
            return command.ExecuteReader(CommandBehavior.CloseConnection);
        }
        protected SqlDataReader ExecuteReader(String procedure, SqlParameter[] parametros)
        {
            OpenConnection();
            command = new SqlCommand(procedure, connection);
            command.CommandType = CommandType.StoredProcedure;
            if (parametros != null)
                command.Parameters.AddRange(parametros);
            return command.ExecuteReader(CommandBehavior.CloseConnection);
        }
        #endregion

        #region ExecuteQueryDataSet
        protected DataSet ExecuteDataSet(String procedure)
        {
            OpenConnection();
            command = new SqlCommand(procedure, connection);
            command.CommandType = CommandType.StoredProcedure;
            adapter = new SqlDataAdapter(command);
            adapter.Fill(dataSet);
            CloseConnection();
            return dataSet;
        }
        protected DataSet ExecuteDataSet(String procedure, SqlParameter[] parametros)
        {
            OpenConnection();
            command = new SqlCommand(procedure, connection);
            command.CommandType = CommandType.StoredProcedure;
            if (parametros != null)
            {
                foreach (SqlParameter param in parametros)
                {
                    command.Parameters.Add(param);
                }
            }
            adapter = new SqlDataAdapter(command);
            adapter.Fill(dataSet);
            CloseConnection();
            return dataSet;
        }
        #endregion

        #endregion

        #region Métodos de Tratamento para MinValue e MaxValue
        public DateTime MinValueDateTime(object objeto)
        {
            return (objeto == null || objeto.ToString() == "") ? DateTime.MinValue : Convert.ToDateTime(objeto);
        }
        public DateTime MaxValueDateTime(object objeto)
        {
            return (objeto == null) ? DateTime.MaxValue : Convert.ToDateTime(objeto);
        }
        public TimeSpan MinValueTimeSpam(object objeto)
        {
            return (objeto == null || objeto.ToString() == "") ? TimeSpan.MinValue : Convert.ToDateTime(objeto).TimeOfDay;
        }
        public int MinValueInt(object objeto)
        {
            return (objeto == null || objeto.ToString() == "") ? int.MinValue : Convert.ToInt32(objeto, CultureInfo.CurrentCulture);
        }
        public decimal MinValueDecimal(object objeto)
        {
            return (objeto == null) ? decimal.MinValue : Convert.ToDecimal(objeto);
        }
        public long MinValueLong(object objeto)
        {
            return (objeto == null) ? long.MinValue : Convert.ToInt64(objeto);
        }
        public String MinValueString(object objeto)
        {
            return (objeto == null) ? String.Empty : Convert.ToString(objeto);
        }
        public Double MinValueDouble(object objeto)
        {
            return (objeto == null) ? Double.MinValue : Convert.ToDouble(objeto);
        }
        public Boolean MinValueBoolean(object objeto)
        {
            return (objeto == null || objeto.ToString() == "") ? false : Convert.ToBoolean(objeto);
        }
        #endregion
        #endregion
    }
}
